package com.hd123.rumba.gwt.widget.client;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.DelegatingChangeListenerCollection;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;

public class LabeledListBox extends HorizontalPanel implements EnterToTab {
  private Label label;
  private ListBox listBox;
  private String caption;
  private boolean required = false;
  private boolean readOnly = false;

  public LabeledListBox() {
    setSpacing(4);

    label = new Label();
    label.setWidth("100px");
    label.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
    add(label);
    setCellVerticalAlignment(label, HorizontalPanel.ALIGN_MIDDLE);

    listBox = new ListBoxE();
    listBox.setVisibleItemCount(1);
    add(listBox);
    setCellVerticalAlignment(listBox, HorizontalPanel.ALIGN_MIDDLE);
  }

  public LabeledListBox(String caption) {
    this();
    setCaption(caption);
  }

  public Label getLabel() {
    return label;
  }

  public ListBox getListBox() {
    return listBox;
  }

  public void setText(String text) {
    int count = getListBox().getItemCount();
    for (int i = 0; i < count; ++i) {
      if (getListBox().getItemText(i).equals(text)) {
        getListBox().setSelectedIndex(i);
        return;
      }
    }
    getListBox().setSelectedIndex(0);
  }

  public String getText() {
    int index = getListBox().getSelectedIndex();
    if (index < 0)
      return null;
    return getListBox().getValue(index);
  }

  public void setCaption(String caption) {
    this.caption = caption;
    if (required && !readOnly)
      DOM.setInnerHTML(label.getElement(), this.caption + "<font color='red'>*</font>");
    else
      getLabel().setText(caption);
  }

  public String getCaption() {
    return getLabel().getText();
  }

  public void setRequired(boolean required) {
    this.required = required;
    setCaption(caption);
  }

  public void addItem(String item) {
    getListBox().addItem(item);
  }

  public void addItem(String item, String value) {
    getListBox().addItem(item, value);
  }

  public void addItems(String[] items) {
    for (int i = 0; i < items.length; ++i)
      getListBox().addItem(items[i]);
  }

  public void setReadOnly(boolean readOnly) {
    this.readOnly = readOnly;
    getListBox().setEnabled(!readOnly);
    setCaption(caption);
  }

  DelegatingChangeListenerCollection changeListeners;

  public void addChangeListener(ChangeListener listener) {
    if (changeListeners == null)
      changeListeners = new DelegatingChangeListenerCollection(this, getListBox());
    changeListeners.add(listener);
  }

  public void removeChangeListener(ChangeListener listener) {
    if (changeListeners != null)
      changeListeners.remove(listener);
  }
}
